from models.message import Message
from models.user import User
from utils import log
from utils import template
from utils import redirect

import random

message_list = []
session = {}
"""
route_static：是原来web1-web5的route
"""


def random_str():
    seed = 'abcdefghijk12345678abcdefghijklmn'
    s = ''
    for i in range(16):
        random_index = random.randint(0, len(seed) - 2)
        s += seed[random_index]
    return s


def template(name):
    path = 'templates/' + name
    with open(path, 'r', encoding='utf-8') as f:
        return f.read()


def current_user(request):
    session_id = request.cookies.get('user', '')
    username = session.get(session_id, '【游客】')
    return username


def route_index(request):
    header = 'HTTP/1.1 210 Very oK \r\nContent-Type:text/html\r\n'
    body = template('index.html')
    username = current_user(request)
    body = body.replace('{{usrename}}', username)
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')


def response_with_headers(headers):
    header = 'HTTP/1.1 210 VERY OK\r\n'
    header += ''.join(['{}:{}\r\n'.format(k, v)
                       for k, v in headers.items()])
    return header


def route_login(request):
    # header = 'HTTP/1.1 210 VERY OK\r\nContent-Type: text/html\r\n'
    headers = {
        'Content-Type': 'text/html',
    }
    username = current_user(request)
    if request.method == 'POST':
        form = request.form()
        u = User(form)
        if u.validate_login():
            # session_id = random_str()
            # session[session_id] = u.username
            # headers['Set-Cookie'] = 'user={}'.format(session_id)
            user = User.find_by(username=u.username)
            session_id = random_str()
            session[session_id] = user.id
            headers['Set-Cookie'] = 'user={}'.format(session_id)
            result = '登陆成功'
            log('headers response', headers)
        else:
            result = '用户名或者密码错误'
    else:
        result = ''
    body = template('login.html')
    body = body.replace('{{result}}', result)
    body = body.replace('{{username}}', username)
    header = response_with_headers(headers)
    r = header + '\r\n' + body
    # log('login的响应', r)
    return r.encode(encoding='utf-8')


def route_register(request):
    header = 'HTTP/1.1 210 VERY OK\r\nContent-Type: text/html\r\n'
    if request.method == 'POST':
        form = request.form()
        # u = User.new(form)
        u = User(form)
        if u.validate_register():
            u.save()
            result = '注册成功<br><pre>{}</pre>'.format(User.all())
        else:
            result = '用户名或者密码长度大于2'
    else:
        result = ''
    body = template('register.html')
    body = body.replace('{{result}}', result)
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')


# def redirect(url):
#     headers = {
#         'Location': url,
#     }
#     r = response_with_headers(headers, 302) + '\r\n'
#     return r.encode('utf-8')


def route_message(request):
    username = current_user(request)
    if username == '【游客】':
        log("**debug,route msg 未登录")
        return redirect('/')
    log('本次请求的method', request.method)
    if request.method == 'POST':
        form = request.form()
        msg = Message.new(form)
        log('post', form)
        message_list.append(msg)
        # 应该在这里保存 message_list
    header = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n'
    body = template('html_basic.html')
    # '#'.join(['a', 'b', 'c']) 的结果是 'a#b#c'
    msgs = '<br>'.join([str(m) for m in message_list])
    body = body.replace('{{messages}}', msgs)
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')


def route_static(request):
    filename = request.query.get('file', )
    path = 'static/' + filename
    with open(path, 'rb') as f:
        # header = b'HTTP/1.1 200 OK\r\nContent-Type: image/gif\r\n\r\n'
        header = b'HTTP/1.1 200 OK\r\n\r\n'
        img = header + f.read()
        return img


route_dict = {
    '/': route_index,
    '/login': route_login,
    '/register': route_register,
    '/message': route_message,
}
